--- 航征HZ-SVR-24Q雷达流量计 modbus 9600,N,8,1
module(..., package.seeall)

local logtag = "HZ24Q"
local dtu, udtu, addr= {}, {} , 0X34
local _t, m_sum,m_val,m_ins,m_sw,m_ls
local status = 1
function setDtu(_dtu, _udtu)
    dtu, udtu = _dtu, _udtu
    addr = udtu.addr and tonumber(udtu.addr) or 0X34
    sys.taskInit(init)
end
--[[ modbus
1-0008  累计水量次数>H，超过1百万自动加1
2-000F	流速 < float 单位 m/h
3-0013	瞬时流量 < float 单位 m3/s
3-0015	水深 < float 单位m
4-0019	累计水量 < float，需要累计次数组合，超过1百万自动清理

]]
local function _pro(d)
    if status == 1 then --累计水量次数
        _t,m_sum = pack.unpack(d:sub(4, -3), ">H")
        status =2
    elseif status==2 then -- 流速 < float 单位 m/h
        _t,m_ls = pack.unpack(d:sub(4, -3), "<f")
        status =3  
    elseif status==3 then --瞬时流量和水深
        _t,m_ins,m_sw = pack.unpack(d:sub(4, -3), "<f2")
        status = 4
    elseif status == 4  then --本次累计
        _t,m_val = pack.unpack(d:sub(4, -3), "<f")
        m_val = m_val and m_val+(m_sum and (m_sum * 1000000) or 0)
        usrdata.update({m_val, m_ins,m_sw,m_ls,"sw:"..m_sw..",ls:"..m_ls})
        if lcd.LCD_DATA[3]:match('累计(.+)') then
            lcd.LCD_DATA[3] ='流量:' .. (m_ins or "NULL")
            return
        end
        lcd.LCD_DATA[3] ='累计:' .. (m_val or "NULL")
        status = 1
    end
end
function init()
    power.openBoost()
    sys.wait(1000)
	while true do
        if status ==1 then 
            tools.modbus_send(3,addr,3,8,1)
        elseif status==2 then
            tools.modbus_send(3,addr,3,0x0f,2)
        elseif status==3 then
            tools.modbus_send(3,addr,3,0x13,4)
        elseif status==4 then
            tools.modbus_send(3,addr,3,0x19,2)
        end
        local result, data = sys.waitUntil("UART_READ_DONE_NEXT_3" , 5000)
        if result then
            _pro(data)
            if status==1 then
                sys.wait(5000)
            end
        else
            lcd.LCD_DATA[3] = logtag.." READ TIMEOUT"
        end
	end
end
